#include "StdAfx.h"
#include "MutableBuffer.h"


MutableBuffer::MutableBuffer(void)
{
	m_buffer=NULL;  
	m_bufferSize=0;  
	m_cursor=0;
}

MutableBuffer::~MutableBuffer(void)
{
	clear();
}

void MutableBuffer::addBuffer(const void* newBuffer,int newBufferSize)
{
	if(!m_buffer)
	{
		m_buffer=new unsigned char[newBufferSize];
		memcpy(m_buffer,newBuffer,newBufferSize);
	}
	else
	{
		unsigned char* oldBuffer=m_buffer;

		m_buffer=new unsigned char[m_bufferSize+newBufferSize];
		memcpy(m_buffer,oldBuffer,m_bufferSize);
		memcpy(m_buffer+m_bufferSize,newBuffer,newBufferSize);

		delete[] oldBuffer;
	}

	m_bufferSize+=newBufferSize;
}

void MutableBuffer::addBuffer(const MutableBuffer* buffer)
{
	addBuffer(buffer->buffer(),buffer->bufferSize());
}

void MutableBuffer::setBuffer(const MutableBuffer* buffer)
{
	setBuffer(buffer->buffer(),buffer->bufferSize());
}

void MutableBuffer::setBuffer(const void* newBuffer,int newBufferSize)
{
	clear();
	addBuffer(newBuffer,newBufferSize);
}


void MutableBuffer::clear()
{
	delete[] m_buffer;
	m_buffer=NULL;
	m_bufferSize=0;
	m_cursor=0;
}

unsigned int MutableBuffer::bufferSize() const
{
	return m_bufferSize;
}
unsigned char* MutableBuffer::buffer() const
{
	return m_buffer;
}

unsigned char* MutableBuffer::allocBuffer() const
{
	unsigned char* buffer=new unsigned char[m_bufferSize];
	memcpy(buffer,m_buffer,m_bufferSize);

	return buffer;
}

unsigned int MutableBuffer::cursoredBufferSize() const
{
	return m_bufferSize-m_cursor;
}

bool MutableBuffer::getCursoredBuffer(MutableBuffer* buffer,float percentageOfAllBuffer)
{
	//TRACE("m_cursor: %d\n",m_cursor);

	if(m_cursor>=m_bufferSize)
	{
		return false;
	}

	bool ret=false;

	unsigned int size=m_bufferSize*percentageOfAllBuffer;
	if(size%2!=0)
	{
		size+=1;
	}

	if(size>m_bufferSize-m_cursor)
	{
		size=m_bufferSize-m_cursor;
	}

	if(size>0)
	{
		buffer->setBuffer(m_buffer+m_cursor,size); 

		ret=true;
	}

	m_cursor+=size;

	return ret;
}
